﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;

namespace DotPowerJob.Middleware
{
    public class PowerJobExecutorMiddleware
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly RequestDelegate _next;
        private readonly PowerJobRestfulServiceHandler _powerJobService;
        public PowerJobExecutorMiddleware(IServiceProvider serviceProvider, RequestDelegate next)
        {
            this._serviceProvider = serviceProvider;
            this._next = next;
            this._powerJobService = this._serviceProvider.GetRequiredService<PowerJobRestfulServiceHandler>();
        }

        public async Task Invoke(HttpContext context)
        {
            string contentType = context.Request.ContentType;

            if ("POST".Equals(context.Request.Method, StringComparison.OrdinalIgnoreCase)
                && !string.IsNullOrEmpty(contentType)
                && contentType.ToLower().StartsWith("application/json")
                && context.Request.Path.Value.StartsWith("/work"))
            {

                await _powerJobService.HandlerAsync(context.Request, context.Response);

                return;
            }

            await _next.Invoke(context);
        }
    }
}
